package com.example.cxx.server.impl;

import com.example.cxx.mapper.UserMapper;
import com.example.cxx.pojo.User;
import com.example.cxx.server.LoginServerce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class LoginSercerceImpl implements LoginServerce {
    @Autowired
    private UserMapper userMapper;
    private User user;
    @Override
    public boolean insertUser(int userAccount, String userPass) {
        user=userMapper.selectUser(userAccount,userPass);
        //学生已经存在的情况
        if(user!=null){
            return true;
        }
        else {
            boolean isAdd=userMapper.insertUser(userAccount,userPass);
            user=userMapper.selectUser(userAccount,userPass);
            return isAdd;
        }



    }


    //插入学号设备对应
    @Override
    public void insertDes(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxf40945fc7a71b3a4&secret=baf507e6d076640e9209400d35e9a24c&js_code=" +code+ "&grant_type=authorization_code";
        RestTemplate client = new RestTemplate();
        String body = client.getForEntity(url, String.class).getBody();
        String[] strings = body.split(",");
        String openid = strings[1].substring(10, strings[1].length()-2);
        if(userMapper.selectDes(openid)){
            userMapper.updateDes(openid,user.getId());
        }else {
            userMapper.insertDes(openid,user.getId());
        }
    }

}
